package com.grq.mis.service;

import com.grq.mis.dao.PermissionDao;
import com.grq.mis.dao.RolePermissionDao;
import com.grq.mis.entity.Permission;
import com.grq.mis.entity.RolePermission;
import com.grq.mis.exception.BusinessException;
import com.grq.mis.exception.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service
public class PermissionService extends BaseService<Permission> {

    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private RolePermissionDao rolePermissionDao;

    public void addPermission(Permission permission) {

        if (permission.getParentId() != 0) {
            Permission parent = permissionDao.single(permission.getParentId());
            if (parent == null) {
                throw new BusinessException(ResultEnum.PARENT_PERMISSION_IS_NULL);
            }
        }
        permissionDao.insert(permission);
    }

    public void updatePermission(Permission model) {
        Permission permission = permissionDao.single(model.getId());
        if (permission == null) {
            throw new BusinessException(ResultEnum.PERMISSION_IS_NULL);
        }

        // 修改
        permission.setName(model.getName());
        permission.setCode(model.getCode());
        permission.setIcon(model.getIcon());
        permission.setUrl(model.getUrl());
        permission.setSort(model.getSort());
        permission.setIsLink(model.getIsLink());

        permissionDao.updateById(permission);
    }


    public void deletePermission(Long id) {
        Permission permission = permissionDao.single(id);
        if (permission == null) {
            throw new BusinessException(ResultEnum.PERMISSION_IS_NULL);
        }

        // 验证子权限
        Long parentCount = permissionDao.createLambdaQuery().andEq(Permission::getParentId, id).count();
        if (parentCount > 0) {
            throw new BusinessException(ResultEnum.PERMISSION_HAS_CHILD, "权限下有" + parentCount + "个子权限，不能删除权限");
        }

        // 删除关联
        rolePermissionDao.createLambdaQuery().andEq(RolePermission::getPermissionId, id).delete();

        // 删除权限
        permissionDao.deleteById(id);
    }
}
